package com.maori.languageapp.curate.phrase;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONObject;
import com.maori.languageapp.R;
import com.maori.languageapp.adapter.Languageapp_Curate_AudioView_Activity;
import com.maori.languageapp.adapter.Languageapp_Curate_VideoView_Activity;
import com.maori.languageapp.consts.ImageLoader;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class Maori_Curate_AudioList_Phrase_Adapter extends BaseAdapter {
	protected static final String TAG = null;
	// Declare Variables
	Context context;
	LayoutInflater inflater;
	ArrayList<HashMap<String, String>> data;
	// Button videoview_example;
	ImageLoader imageLoader;
	String UserLikedAudio,AudioParentNID,UserCurateStateAudio,AudioParentUID,AudioNID,result,AudioMediaID,TotalsSetDefaultAudio,SynMediaType,SynUserID,SynNodeId,SynParentNodeId;
	private MediaPlayer mediaPlayer;
	int timeoutConnection = 5000;
	HttpParams httpParameters = new BasicHttpParams();
	InputStream is = null;
	StringBuilder sb = null;
	private LayoutInflater mInflater;
	HashMap<String, String> resultp = new HashMap<String, String>();
	String MediaUID,NodeMediaType,ApproveState,AudioMediaRefNo;

	//*************Audio Dialog Controller*************

	private double startTime = 0;
	private double finalTime = 0;
	private Handler myHandler = new Handler();;
	private int forwardTime = 1000;
	private int backwardTime = 1000;
	public static int oneTimeOnly = 0;

	SeekBar seekbar;
	Button btn_pause_active, btn_play, btn_pause, btn_play_active;
	
	//*************************************************
	
	
	public Maori_Curate_AudioList_Phrase_Adapter(Context context,
			ArrayList<HashMap<String, String>> arraylist) {
		this.context = context;
		data = arraylist;
		imageLoader = new ImageLoader(context);
		mInflater = LayoutInflater.from(context);
	}

	@Override
	public int getCount() {
		return data.size();
	}

	@Override
	public Object getItem(int position) {
		return data.get(position);
	}

	@Override
	public long getItemId(int position) {
		 return position;
	}

	public View getView(final int position, View convertView, ViewGroup parent) {
		// Declare Variables
		final ViewHolder holder;
		 if (convertView == null) {
		        convertView = mInflater.inflate(R.layout.languageapp_curate_audio, null);
		        holder = new ViewHolder();
		        holder.first_name = (TextView) convertView.findViewById(R.id.firstname);
		        holder.user_role = (TextView) convertView.findViewById(R.id.lastname);
		        holder.display_dialect = (Button) convertView.findViewById(R.id.display_dialect);
		        holder.display_location = (Button) convertView.findViewById(R.id.display_location);
		        holder.userimage = (ImageView) convertView.findViewById(R.id.userimggriditem);
		        holder.setApproveAction = (Button) convertView.findViewById(R.id.setApproveAction);
		        holder.setModifyAction = (Button) convertView.findViewById(R.id.setModifyAction);
		        holder.setRejectAction = (Button) convertView.findViewById(R.id.setRejectAction);
		        holder.urlreader = (Button) convertView.findViewById(R.id.urlreader);
		        
		     
		        convertView.setTag(holder);
		    } else {
		        holder = (ViewHolder) convertView.getTag();
		    }


		resultp = data.get(position);
	

		imageLoader.DisplayImage(resultp.get(Maori_Curate_Phrase_Details.getIMAGEMID()), holder.userimage);
		holder.first_name.setText(resultp.get(Maori_Curate_Phrase_Details.getIMAGEfirst_name()) + " " +resultp.get(Maori_Curate_Phrase_Details.getIMAGElast_name()));
		holder.user_role.setText(resultp.get(Maori_Curate_Phrase_Details.getSYNtribe()));
		holder.display_dialect.setText(resultp.get(Maori_Curate_Phrase_Details.getAudioSyndialact()));
		holder.display_location.setText(resultp.get(Maori_Curate_Phrase_Details.getSYNcurrent_location()));
		
		MediaUID = resultp.get(Maori_Curate_Phrase_Details.getMediaUID());
		NodeMediaType = resultp.get(Maori_Curate_Phrase_Details.getNodeMediaType());
		
		UserLikedAudio = resultp.get(Maori_Curate_Phrase_Details.getUserLikedAudio());
		AudioParentNID = resultp.get(Maori_Curate_Phrase_Details.getAudioParentNID());
		AudioParentUID = resultp.get(Maori_Curate_Phrase_Details.getAudioParentUID());
		TotalsSetDefaultAudio = resultp.get(Maori_Curate_Phrase_Details.getTotalsSetDefaultAudio());
		UserCurateStateAudio = resultp.get(Maori_Curate_Phrase_Details.getUserCurateStateAudio());
		
		/********** if user liked Like Button Set to Active ******************/

		if(UserCurateStateAudio.equals("1")){
			holder.setApproveAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_active, 0, 0, 0);
			holder.setApproveAction.setEnabled(false);
		}
		else if(UserCurateStateAudio.equals("2")){
			holder.setRejectAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_reject_active, 0, 0, 0);
			holder.setRejectAction.setEnabled(false);
		}
		else if(UserCurateStateAudio.equals("3")){
			holder.setModifyAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_modify_active, 0, 0, 0);
			holder.setModifyAction.setEnabled(false);
		}
		
		
		
		holder.setApproveAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				resultp = data.get(position);
				SynUserID = resultp.get(Maori_Curate_Phrase_Details.getUIDuser());
				SynNodeId = resultp.get(Maori_Curate_Phrase_Details.getSYNNID());
				AudioParentNID = resultp.get(Maori_Curate_Phrase_Details.getAudioParentNID());
				AudioMediaRefNo = resultp.get(Maori_Curate_Phrase_Details.getIMAGENM_ID());
				SynMediaType = "2";
				ApproveState = "1";
				
				holder.setApproveAction.setEnabled(false);
				holder.setApproveAction.setText("Approve");
				holder.setApproveAction.setTextColor(Color.parseColor("#07afdf"));
				holder.setApproveAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_active, 0, 0, 0);
				
				holder.setRejectAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_reject_inactive, 0, 0, 0);
				holder.setRejectAction.setTextColor(Color.parseColor("#626262"));
				holder.setRejectAction.setEnabled(true);
				holder.setModifyAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_modify_inactive, 0, 0, 0);
				holder.setModifyAction.setTextColor(Color.parseColor("#626262"));
				holder.setModifyAction.setEnabled(true);
				
				
				new UploadApprovalInformation().execute();
			}
		});
		
		
		holder.setRejectAction.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				resultp = data.get(position);
				SynUserID = resultp.get(Maori_Curate_Phrase_Details.getUIDuser());
				AudioParentNID = resultp.get(Maori_Curate_Phrase_Details.getAudioParentNID());
				SynParentNodeId = resultp.get(Maori_Curate_Phrase_Details.getSYNParentNID());
				AudioMediaRefNo = resultp.get(Maori_Curate_Phrase_Details.getIMAGENM_ID());
				SynMediaType = "2";
				ApproveState = "2";
				final Dialog dialog=new Dialog(context);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.languageapp_curate_reject_form);
				
				Button rejectaccept=(Button)dialog.findViewById(R.id.rejectaccept);
				rejectaccept.setOnClickListener(new View.OnClickListener() {
					public void onClick(View view) {
						
						holder.setRejectAction.setEnabled(false);
						holder.setRejectAction.setText("Reject");
						holder.setRejectAction.setTextColor(Color.parseColor("#07afdf"));
						holder.setRejectAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_reject_active, 0, 0, 0);
						
						holder.setApproveAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_default_inactive, 0, 0, 0);
						holder.setApproveAction.setTextColor(Color.parseColor("#626262"));
						holder.setApproveAction.setEnabled(true);
						holder.setModifyAction.setCompoundDrawablesWithIntrinsicBounds(R.drawable.ic_modify_inactive, 0, 0, 0);
						holder.setModifyAction.setTextColor(Color.parseColor("#626262"));
						holder.setModifyAction.setEnabled(true);

						new UploadApprovalInformation().execute();
						dialog.dismiss();
					}
				});
				
				Button rejectcancel=(Button)dialog.findViewById(R.id.rejectcancel);
				rejectcancel.setOnClickListener(new View.OnClickListener() {
					public void onClick(View view) {
						dialog.dismiss();
					}
				});
				dialog.show();
			}
		});
		
		holder.urlreader.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// Get the position from the results
				
				final Dialog dialog = new Dialog(context);
				dialog.setContentView(R.layout.language_app_audio_dialog);
				dialog.setTitle("Play Audio");

				seekbar = (SeekBar) dialog.findViewById(R.id.seekbaraudio);
				btn_pause_active = (Button) dialog.findViewById(R.id.btn_pause_active);
				btn_play = (Button) dialog.findViewById(R.id.btn_play);
				btn_pause = (Button) dialog.findViewById(R.id.btn_pause);
				btn_play_active = (Button) dialog.findViewById(R.id.btn_play_active);

				btn_play.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						playAudio(v);
					}
				});

				btn_pause.setOnClickListener(new OnClickListener() {

					public void onClick(View v) {
						pauseAudio(v);
					}
				});
				
				
				HashMap<String, String> resultp = new HashMap<String, String>();
				resultp = data.get(position);
				String AudioUrlSource =resultp.get(Maori_Curate_Phrase_Details.getIMAGEM_Source());
				
				mediaPlayer = new MediaPlayer();
				mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
				try {
					mediaPlayer.setDataSource(AudioUrlSource);
					mediaPlayer.prepare();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IllegalStateException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}
				
				//mediaPlayer.start();
				seekbar.setClickable(false);
				btn_pause.setEnabled(false);
				dialog.show();
			}
		});
		return convertView;
	}
	
	
	static class ViewHolder {
		Button setRejectAction;
		Button setModifyAction;
		Button setApproveAction;
		Button urlreader;
		TextView first_name;
		TextView last_name;
		TextView  user_role;
		ImageView userimage;
		Button display_location;
		Button display_dialect;
		ImageView flag;

	}
	
	private class UploadApprovalInformation extends AsyncTask<Void, Void, Void> {
		private final String TAG = null;

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			try {
				HttpPost httppost = null;
				HttpConnectionParams.setConnectionTimeout(httpParameters,
						timeoutConnection);
				HttpClient httpclient = new DefaultHttpClient(httpParameters);
				JSONObject json = new JSONObject();
				httppost = new HttpPost(
						"http://langapp.mirzabros.com/maoriapi/curate/SaveCurateApprovalMediaInfo.php");

				json.put("record1", AudioParentUID); // $approve_user
				json.put("record2", ApproveState); // $approve_state
				json.put("record3", AudioParentNID); // $approve_node
				json.put("record4", SynMediaType); // $approve_media
				json.put("record5", AudioMediaRefNo); // $approve_media_id
	
				JSONArray postjson = new JSONArray();
				postjson.put(json);
				Log.v("TAG","POST SET DEF : " + postjson);
				httppost.setHeader("json", json.toString());
				httppost.getParams().setParameter("jsonpost", postjson);
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
				HttpResponse response = httpclient.execute(httppost);
				HttpEntity entity = response.getEntity();
				is = entity.getContent();
				if (is != null) {

					BufferedReader reader = new BufferedReader(
							new InputStreamReader(is, "iso-8859-1"), 8);
					sb = new StringBuilder();
					sb.append(reader.readLine() + "\n");
					String line = "0";

					while ((line = reader.readLine()) != null) {
						sb.append(line + "\n");
					}
					is.close();
					result = sb.toString();
					Log.v("TAG", "Print RES ***:" + result);
					if (result != null) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {
			
		}
	}
	
	//*************Audio Dialog Controller*************
		class UpdateSongTime implements Runnable {

			private SeekBar seek;

			public UpdateSongTime() {
				// TODO Auto-generated constructor stub
			}

			public UpdateSongTime(SeekBar seekbar) {
				// TODO Auto-generated constructor stub
				this.seek = seekbar;
			}

			@Override
			public void run() {
				startTime = mediaPlayer.getCurrentPosition();
				seek.setProgress((int) startTime);
				myHandler.postDelayed(this, 100);
			}

		}
		public void playAudio(View view) {
			mediaPlayer.start();
			finalTime = mediaPlayer.getDuration();
			startTime = mediaPlayer.getCurrentPosition();
			if (oneTimeOnly == 0) {
				seekbar.setMax((int) finalTime);
				oneTimeOnly = 1;
			}

			btn_pause_active.setText(String.format(
					"%d min, %d sec",
					TimeUnit.MILLISECONDS.toMinutes((long) finalTime),
					TimeUnit.MILLISECONDS.toSeconds((long) finalTime)
							- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
									.toMinutes((long) finalTime))));
			btn_play_active.setText(String.format(
					"%d min, %d sec",
					TimeUnit.MILLISECONDS.toMinutes((long) startTime),
					TimeUnit.MILLISECONDS.toSeconds((long) startTime)
							- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
									.toMinutes((long) startTime))));
			seekbar.setProgress((int) startTime);
			myHandler.postDelayed(UpdateSongTime, 100);
			btn_pause.setEnabled(true);
			btn_play.setEnabled(false);
		}
		
		private Runnable UpdateSongTime = new Runnable() {
			public void run() {
				startTime = mediaPlayer.getCurrentPosition();
				btn_play_active.setText(String.format(
						"%d min, %d sec",
						TimeUnit.MILLISECONDS.toMinutes((long) startTime),
						TimeUnit.MILLISECONDS.toSeconds((long) startTime)
								- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
										.toMinutes((long) startTime))));
				seekbar.setProgress((int) startTime);
				myHandler.postDelayed(this, 100);
			}
		};
		public void pauseAudio(View view) {
			mediaPlayer.pause();
			btn_pause.setEnabled(false);
			btn_play.setEnabled(true);
		}
		
	
}